{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "xAcWoT058AsC"
   },
   "source": [
    "##### Copyright 2020 The TensorFlow Authors."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "cellView": "form",
    "colab": {},
    "colab_type": "code",
    "id": "SrP0JCAoQ7Ic"
   },
   "outputs": [],
   "source": [
    "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "# you may not use this file except in compliance with the License.\n",
    "# You may obtain a copy of the License at\n",
    "#\n",
    "# https://www.apache.org/licenses/LICENSE-2.0\n",
    "#\n",
    "# Unless required by applicable law or agreed to in writing, software\n",
    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "# See the License for the specific language governing permissions and\n",
    "# limitations under the License."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "LRWtHBCaetX1"
   },
   "source": [
    "# The Functional API"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "jMCGqNgmeyeC"
   },
   "source": [
    "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://www.tensorflow.org/guide/keras/functional\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on TensorFlow.org</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/guide/keras/functional.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://github.com/keras-team/keras-io/blob/master/guides/functional_api.py\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a href=\"https://storage.googleapis.com/tensorflow_docs/docs/site/en/guide/keras/functional.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n",
    "  </td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "D5NkT1ePyhWP"
   },
   "source": [
    "## Setup"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code",
    "id": "j4Jf1p0nJwT4"
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "from tensorflow import keras\n",
    "from tensorflow.keras import layers"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "c2t3ghLSpKWd"
   },
   "source": [
    "## Introduction\n",
    "\n",
    "The Keras *functional API* is a way to create models that is more flexible\n",
    "than the `tf.keras.Sequential` API. The functional API can handle models\n",
    "with non-linear topology, models with shared layers, and models\n",
    "with multiple inputs or outputs.\n",
    "\n",
    "The main idea that a deep learning model is usually\n",
    "a directed acyclic graph (DAG) of layers.\n",
    "So the functional API is a way to build *graphs of layers*.\n",
    "\n",
    "Consider the following model:\n",
    "\n",
    "```\n",
    "(input: 784-dimensional vectors)\n",
    "       \u21a7\n",
    "[Dense (64 units, relu activation)]\n",
    "       \u21a7\n",
    "[Dense (64 units, relu activation)]\n",
    "       \u21a7\n",
    "[Dense (10 units, softmax activation)]\n",
    "       \u21a7\n",
    "(output: logits of a probability distribution over 10 classes)\n",
    "```\n",
    "\n",
    "This is a basic graph with three layers.\n",
    "To build this model using the functional API, start by creating an input node:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code",
    "id": "tj0VaXMBc0m9"
   },
   "outputs": [],
   "source": [
    "inputs = keras.Input(shape=(784,))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "JZ3TkPwJmzFE"
   },
   "source": [
    "The shape of the data is set as a 784-dimensional vector.\n",
    "The batch size is always omitted since only the shape of each sample is specified.\n",
    "\n",
    "If, for example, you have an image input with a shape of `(32, 32, 3)`,\n",
    "you would use:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code",
    "id": "Ni4NURDXFV8o"
   },
   "outputs": [],
   "source": [
    "# Just for demonstration purposes.\n",
    "img_inputs = keras.Input(shape=(32, 32, 3))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "BTohLQzqtZp0"
   },
   "source": [
    "The `inputs` that is returned contains information about the shape and `dtype`\n",
    "of the input data that you feed to your model.\n",
    "Here's the shape:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code",
    "id": "e3d5w05cqerx"
   },
   "outputs": [],
   "source": [
    "inputs.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "oqTiX78hj1EL"
   },
   "source": [
    "Here's the dtype:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code",
    "id": "ntF4i5G4OmMh"
   },
   "outputs": [],
   "source": [
    "inputs.dtype"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "eHKpRryjucCS"
   },
   "source": [
    "You create a new node in the graph of layers by calling a layer on this `inputs`\n",
    "object:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code",
    "id": "z9UtvF7cNV3Y"
   },
   "outputs": [],
   "source": [
    "dense = layers.Dense(64, activation=\"relu\")\n",
    "x = dense(inputs)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "zLk711x0SptV"
   },
   "source": [
    "The \"layer call\" action is like drawing an arrow from \"inputs\" to this layer\n",
    "you created.\n",
    "You're \"passing\" the inputs to the `dense` layer, and out you get `x`.\n",
    "\n",
    "Let's add a few more layers to the graph of layers:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code",
    "id": "kyPCuPnaExTu"
   },
   "outputs": [],
   "source": [
    "x = layers.Dense(64, activation=\"relu\")(x)\n",
    "outputs = layers.Dense(10)(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "5bRiQXFJNPVY"
   },
   "source": [
    "At this point, you can create a `Model` by specifying its inputs and outputs\n",
    "in the graph of layers:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code",
    "id": "NlbsUTz4ediP"
   },
   "outputs": [],
   "source": [
    "model = keras.Model(inputs=inputs, outputs=outputs, name=\"mnist_model\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "ZR2EBOkR02ki"
   },
   "source": [
    "Let's check out what the model summary looks like:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code",
    "id": "c6DsK98aegRP"
   },
   "outputs": [],
   "source": [
    "model.summary()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "wfIqDtsMfjZ5"
   },
   "source": [
    "You can also plot the model as a graph:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code",
    "id": "dQHRFS7WXzQv"
   },
   "outputs": [],
   "source": [
    "keras.utils.plot_model(model, \"my_first_model.png\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "4bJ57WRL1rhh"
   },
   "source": [
    "And, optionally, display the input and output shapes of each layer\n",
    "in the plotted graph:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code",
    "id": "hkrxei4Y5rTH"
   },
   "outputs": [],
   "source": [
    "keras.utils.plot_model(model, \"my_first_model_with_shape_info.png\", show_shapes=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "sjUYpr0DQIQf"
   },
   "source": [
    "This figure and the code are almost identical. In the code version,\n",
    "the connection arrows are replaced by the call operation.\n",
    "\n",
    "A \"graph of layers\" is an intuitive mental image for a deep learning model,\n",
    "and the functional API is a way to create models that closely mirror this."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "uBEjZde4ONBQ"
   },
   "source": [
    "## Training, evaluation, and inference\n",
    "\n",
    "Training, evaluation, and inference work exactly in the same way for models\n",
    "built using the functional API as for `Sequential` models.\n",
    "\n",
    "Here, load the MNIST image data, reshape it into vectors,\n",
    "fit the model on the data (while monitoring performance on a validation split),\n",
    "then evaluate the model on the test data:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code",
    "id": "3R5rGsN8iQXk"
   },
   "outputs": [],
   "source": [
    "(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()\n",
    "\n",
    "x_train = x_train.reshape(60000, 784).astype(\"float32\") / 255\n",
    "x_test = x_test.reshape(10000, 784).astype(\"float32\") / 255\n",
    "\n",
    "model.compile(\n",
    "    loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n",
    "    optimizer=keras.optimizers.RMSprop(),\n",
    "    metrics=[\"accuracy\"],\n",
    ")\n",
    "\n",
    "history = model.fit(x_train, y_train, batch_size=64, epochs=2, validation_split=0.2)\n",
    "\n",
    "test_scores = model.evaluate(x_test, y_test, verbose=2)\n",
    "print(\"Test loss:\", test_scores[0])\n",
    "print(\"Test accuracy:\", test_scores[1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "XjadEAtafoKv"
   },
   "source": [
    "For further reading, see the [training and evaluation](https://www.tensorflow.org/guide/keras/train_and_evaluate/) guide."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "oy01zE6gf4qo"
   },
   "source": [
    "## Save and serialize\n",
    "\n",
    "Saving the model and serialization work the same way for models built using\n",
    "the functional API as they do for `Sequential` models. To standard way\n",
    "to save a functional model is to call `model.save()`\n",
    "to save the entire model as a single file. You can later recreate the same model\n",
    "from this file, even if the code that built the model is no longer available.\n",
    "\n",
    "This saved file includes the:\n",
    "- model architecture\n",
    "- model weight values (that were learned during training)\n",
    "- model training config, if any (as passed to `compile`)\n",
    "- optimizer and its state, if any (to restart training where you left off)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code",
    "id": "Dq61T4ZTsNLG"
   },
   "outputs": [],
   "source": [
    "model.save(\"path_to_my_model\")\n",
    "del model\n",
    "# Recreate the exact same model purely from the file:\n",
    "model = keras.models.load_model(\"path_to_my_model\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "DylMipYNjkjj"
   },
   "source": [
    "For details, read the model [serialization & saving](\n",
    "https://www.tensorflow.org/guide/keras/save_and_serialize/) guide."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "VhLW0qCy37mR"
   },
   "source": [
    "## Use the same graph of layers to define multiple models\n",
    "\n",
    "In the functional API, models are created by specifying their inputs\n",
    "and outputs in a graph of layers. That means that a single\n",
    "graph of layers can be used to generate multiple models.\n",
    "\n",
    "In the example below, you use the same stack of layers to instantiate two models:\n",
    "an `encoder` model that turns image inputs into 16-dimensional vectors,\n",
    "and an end-to-end `autoencoder` model for training."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code",
    "id": "ODrqVnpseqzj"
   },
   "outputs": [],
   "source": [
    "encoder_input = keras.Input(shape=(28, 28, 1), name=\"img\")\n",
    "x = layers.Conv2D(16, 3, activation=\"relu\")(encoder_input)\n",
    "x = layers.Conv2D(32, 3, activation=\"relu\")(x)\n",
    "x = layers.MaxPooling2D(3)(x)\n",
    "x = layers.Conv2D(32, 3, activation=\"relu\")(x)\n",
    "x = layers.Conv2D(16, 3, activation=\"relu\")(x)\n",
    "encoder_output = layers.GlobalMaxPooling2D()(x)\n",
    "\n",
    "encoder = keras.Model(encoder_input, encoder_output, name=\"encoder\")\n",
    "encoder.summary()\n",
    "\n",
    "x = layers.Reshape((4, 4, 1))(encoder_output)\n",
    "x = layers.Conv2DTranspose(16, 3, activation=\"relu\")(x)\n",
    "x = layers.Conv2DTranspose(32, 3, activation=\"relu\")(x)\n",
    "x = layers.UpSampling2D(3)(x)\n",
    "x = layers.Conv2DTranspose(16, 3, activation=\"relu\")(x)\n",
    "decoder_output = layers.Conv2DTranspose(1, 3, activation=\"relu\")(x)\n",
    "\n",
    "autoencoder = keras.Model(encoder_input, decoder_output, name=\"autoencoder\")\n",
    "autoencoder.summary()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "J3Tz8lQIDnAG"
   },
   "source": [
    "Here, the decoding architecture is strictly symmetrical\n",
    "to the encoding architecture, so the output shape is the same as\n",
    "the input shape `(28, 28, 1)`.\n",
    "\n",
    "The reverse of a `Conv2D` layer is a `Conv2DTranspose` layer,\n",
    "and the reverse of a `MaxPooling2D` layer is an `UpSampling2D` layer."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "6tKFv785CYd4"
   },
   "source": [
    "## All models are callable, just like layers\n",
    "\n",
    "You can treat any model as if it were a layer by invoking it on an `Input` or\n",
    "on the output of another layer. By calling a model you aren't just reusing\n",
    "the architecture of the model, you're also reusing its weights.\n",
    "\n",
    "To see this in action, here's a different take on the autoencoder example that\n",
    "creates an encoder model, a decoder model, and chain them in two calls\n",
    "to obtain the autoencoder model:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code",
    "id": "iUYUf0iAeeOU"
   },
   "outputs": [],
   "source": [
    "encoder_input = keras.Input(shape=(28, 28, 1), name=\"original_img\")\n",
    "x = layers.Conv2D(16, 3, activation=\"relu\")(encoder_input)\n",
    "x = layers.Conv2D(32, 3, activation=\"relu\")(x)\n",
    "x = layers.MaxPooling2D(3)(x)\n",
    "x = layers.Conv2D(32, 3, activation=\"relu\")(x)\n",
    "x = layers.Conv2D(16, 3, activation=\"relu\")(x)\n",
    "encoder_output = layers.GlobalMaxPooling2D()(x)\n",
    "\n",
    "encoder = keras.Model(encoder_input, encoder_output, name=\"encoder\")\n",
    "encoder.summary()\n",
    "\n",
    "decoder_input = keras.Input(shape=(16,), name=\"encoded_img\")\n",
    "x = layers.Reshape((4, 4, 1))(decoder_input)\n",
    "x = layers.Conv2DTranspose(16, 3, activation=\"relu\")(x)\n",
    "x = layers.Conv2DTranspose(32, 3, activation=\"relu\")(x)\n",
    "x = layers.UpSampling2D(3)(x)\n",
    "x = layers.Conv2DTranspose(16, 3, activation=\"relu\")(x)\n",
    "decoder_output = layers.Conv2DTranspose(1, 3, activation=\"relu\")(x)\n",
    "\n",
    "decoder = keras.Model(decoder_input, decoder_output, name=\"decoder\")\n",
    "decoder.summary()\n",
    "\n",
    "autoencoder_input = keras.Input(shape=(28, 28, 1), name=\"img\")\n",
    "encoded_img = encoder(autoencoder_input)\n",
    "decoded_img = decoder(encoded_img)\n",
    "autoencoder = keras.Model(autoencoder_input, decoded_img, name=\"autoencoder\")\n",
    "autoencoder.summary()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "6DB1NuEJHeMJ"
   },
   "source": [
    "As you can see, the model can be nested: a model can contain sub-models\n",
    "(since a model is just like a layer).\n",
    "A common use case for model nesting is *ensembling*.\n",
    "For example, here's how to ensemble a set of models into a single model\n",
    "that averages their predictions:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code",
    "id": "hb1XRUeQVjzY"
   },
   "outputs": [],
   "source": [
    "\n",
    "def get_model():\n",
    "    inputs = keras.Input(shape=(128,))\n",
    "    outputs = layers.Dense(1)(inputs)\n",
    "    return keras.Model(inputs, outputs)\n",
    "\n",
    "\n",
    "model1 = get_model()\n",
    "model2 = get_model()\n",
    "model3 = get_model()\n",
    "\n",
    "inputs = keras.Input(shape=(128,))\n",
    "y1 = model1(inputs)\n",
    "y2 = model2(inputs)\n",
    "y3 = model3(inputs)\n",
    "outputs = layers.average([y1, y2, y3])\n",
    "ensemble_model = keras.Model(inputs=inputs, outputs=outputs)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "gHX6x7K7VKsw"
   },
   "source": [
    "## Manipulate complex graph topologies\n",
    "\n",
    "### Models with multiple inputs and outputs\n",
    "\n",
    "The functional API makes it easy to manipulate multiple inputs and outputs.\n",
    "This cannot be handled with the `Sequential` API.\n",
    "\n",
    "For example, if you're building a system for ranking custom issue tickets by\n",
    "priority and routing them to the correct department,\n",
    "then the model will have three inputs:\n",
    "\n",
    "- the title of the ticket (text input),\n",
    "- the text body of the ticket (text input), and\n",
    "- any tags added by the user (categorical input)\n",
    "\n",
    "This model will have two outputs:\n",
    "\n",
    "- the priority score between 0 and 1 (scalar sigmoid output), and\n",
    "- the department that should handle the ticket (softmax output\n",
    "over the set of departments).\n",
    "\n",
    "You can build this model in a few lines with the functional API:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code",
    "id": "AxZ5GovQ9iwI"
   },
   "outputs": [],
   "source": [
    "num_tags = 12  # Number of unique issue tags\n",
    "num_words = 10000  # Size of vocabulary obtained when preprocessing text data\n",
    "num_departments = 4  # Number of departments for predictions\n",
    "\n",
    "title_input = keras.Input(\n",
    "    shape=(None,), name=\"title\"\n",
    ")  # Variable-length sequence of ints\n",
    "body_input = keras.Input(shape=(None,), name=\"body\")  # Variable-length sequence of ints\n",
    "tags_input = keras.Input(\n",
    "    shape=(num_tags,), name=\"tags\"\n",
    ")  # Binary vectors of size `num_tags`\n",
    "\n",
    "# Embed each word in the title into a 64-dimensional vector\n",
    "title_features = layers.Embedding(num_words, 64)(title_input)\n",
    "# Embed each word in the text into a 64-dimensional vector\n",
    "body_features = layers.Embedding(num_words, 64)(body_input)\n",
    "\n",
    "# Reduce sequence of embedded words in the title into a single 128-dimensional vector\n",
    "title_features = layers.LSTM(128)(title_features)\n",
    "# Reduce sequence of embedded words in the body into a single 32-dimensional vector\n",
    "body_features = layers.LSTM(32)(body_features)\n",
    "\n",
    "# Merge all available features into a single large vector via concatenation\n",
    "x = layers.concatenate([title_features, body_features, tags_input])\n",
    "\n",
    "# Stick a logistic regression for priority prediction on top of the features\n",
    "priority_pred = layers.Dense(1, name=\"priority\")(x)\n",
    "# Stick a department classifier on top of the features\n",
    "department_pred = layers.Dense(num_departments, name=\"department\")(x)\n",
    "\n",
    "# Instantiate an end-to-end model predicting both priority and department\n",
    "model = keras.Model(\n",
    "    inputs=[title_input, body_input, tags_input],\n",
    "    outputs=[priority_pred, department_pred],\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "Hd5UJkxqefGX"
   },
   "source": [
    "Now plot the model:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code",
    "id": "WSUStRlwKbc7"
   },
   "outputs": [],
   "source": [
    "keras.utils.plot_model(model, \"multi_input_and_output_model.png\", show_shapes=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "u2Hn9KgQpVg7"
   },
   "source": [
    "When compiling this model, you can assign different losses to each output.\n",
    "You can even assign different weights to each loss -- to modulate\n",
    "their contribution to the total training loss."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code",
    "id": "7yBjMbtIYRaH"
   },
   "outputs": [],
   "source": [
    "model.compile(\n",
    "    optimizer=keras.optimizers.RMSprop(1e-3),\n",
    "    loss=[\n",
    "        keras.losses.BinaryCrossentropy(from_logits=True),\n",
    "        keras.losses.CategoricalCrossentropy(from_logits=True),\n",
    "    ],\n",
    "    loss_weights=[1.0, 0.2],\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "VSPUBE5SUbfM"
   },
   "source": [
    "Since the output layers have different names, you could also specify\n",
    "the loss like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code",
    "id": "ZRguurreYcEB"
   },
   "outputs": [],
   "source": [
    "model.compile(\n",
    "    optimizer=keras.optimizers.RMSprop(1e-3),\n",
    "    loss={\n",
    "        \"priority\": keras.losses.BinaryCrossentropy(from_logits=True),\n",
    "        \"department\": keras.losses.CategoricalCrossentropy(from_logits=True),\n",
    "    },\n",
    "    loss_weights=[1.0, 0.2],\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "X0rjIvSz4klg"
   },
   "source": [
    "Train the model by passing lists of NumPy arrays of inputs and targets:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code",
    "id": "kwruHyKwvuh8"
   },
   "outputs": [],
   "source": [
    "# Dummy input data\n",
    "title_data = np.random.randint(num_words, size=(1280, 10))\n",
    "body_data = np.random.randint(num_words, size=(1280, 100))\n",
    "tags_data = np.random.randint(2, size=(1280, num_tags)).astype(\"float32\")\n",
    "\n",
    "# Dummy target data\n",
    "priority_targets = np.random.random(size=(1280, 1))\n",
    "dept_targets = np.random.randint(2, size=(1280, num_departments))\n",
    "\n",
    "model.fit(\n",
    "    {\"title\": title_data, \"body\": body_data, \"tags\": tags_data},\n",
    "    {\"priority\": priority_targets, \"department\": dept_targets},\n",
    "    epochs=2,\n",
    "    batch_size=32,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "hM8r8KCzWoFP"
   },
   "source": [
    "When calling fit with a `Dataset` object, it should yield either a\n",
    "tuple of lists like `([title_data, body_data, tags_data], [priority_targets, dept_targets])`\n",
    "or a tuple of dictionaries like\n",
    "`({'title': title_data, 'body': body_data, 'tags': tags_data}, {'priority': priority_targets, 'department': dept_targets})`.\n",
    "\n",
    "For more detailed explanation, refer to the [training and evaluation](https://www.tensorflow.org/guide/keras/train_and_evaluate/) guide."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "Feb9uwIWSTui"
   },
   "source": [
    "### A toy ResNet model\n",
    "\n",
    "In addition to models with multiple inputs and outputs,\n",
    "the functional API makes it easy to manipulate non-linear connectivity\n",
    "topologies -- these are models with layers that are not connected sequentially.\n",
    "Something the `Sequential` API can not handle.\n",
    "\n",
    "A common use case for this is residual connections.\n",
    "Let's build a toy ResNet model for CIFAR10 to demonstrate this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code",
    "id": "jw54LoTDsBAP"
   },
   "outputs": [],
   "source": [
    "inputs = keras.Input(shape=(32, 32, 3), name=\"img\")\n",
    "x = layers.Conv2D(32, 3, activation=\"relu\")(inputs)\n",
    "x = layers.Conv2D(64, 3, activation=\"relu\")(x)\n",
    "block_1_output = layers.MaxPooling2D(3)(x)\n",
    "\n",
    "x = layers.Conv2D(64, 3, activation=\"relu\", padding=\"same\")(block_1_output)\n",
    "x = layers.Conv2D(64, 3, activation=\"relu\", padding=\"same\")(x)\n",
    "block_2_output = layers.add([x, block_1_output])\n",
    "\n",
    "x = layers.Conv2D(64, 3, activation=\"relu\", padding=\"same\")(block_2_output)\n",
    "x = layers.Conv2D(64, 3, activation=\"relu\", padding=\"same\")(x)\n",
    "block_3_output = layers.add([x, block_2_output])\n",
    "\n",
    "x = layers.Conv2D(64, 3, activation=\"relu\")(block_3_output)\n",
    "x = layers.GlobalAveragePooling2D()(x)\n",
    "x = layers.Dense(256, activation=\"relu\")(x)\n",
    "x = layers.Dropout(0.5)(x)\n",
    "outputs = layers.Dense(10)(x)\n",
    "\n",
    "model = keras.Model(inputs, outputs, name=\"toy_resnet\")\n",
    "model.summary()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "R1g137Bztb4r"
   },
   "source": [
    "Plot the model:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code",
    "id": "hiugOwVqaoMC"
   },
   "outputs": [],
   "source": [
    "keras.utils.plot_model(model, \"mini_resnet.png\", show_shapes=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "nasrpG3keHpL"
   },
   "source": [
    "Now train the model:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code",
    "id": "ylmTYKVNlmjv"
   },
   "outputs": [],
   "source": [
    "(x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data()\n",
    "\n",
    "x_train = x_train.astype(\"float32\") / 255.0\n",
    "x_test = x_test.astype(\"float32\") / 255.0\n",
    "y_train = keras.utils.to_categorical(y_train, 10)\n",
    "y_test = keras.utils.to_categorical(y_test, 10)\n",
    "\n",
    "model.compile(\n",
    "    optimizer=keras.optimizers.RMSprop(1e-3),\n",
    "    loss=keras.losses.CategoricalCrossentropy(from_logits=True),\n",
    "    metrics=[\"acc\"],\n",
    ")\n",
    "# We restrict the data to the first 1000 samples so as to limit execution time\n",
    "# on Colab. Try to train on the entire dataset until convergence!\n",
    "model.fit(x_train[:1000], y_train[:1000], batch_size=64, epochs=1, validation_split=0.2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "7ZcyVlDOdCas"
   },
   "source": [
    "## Shared layers\n",
    "\n",
    "Another good use for the functional API are for models that use *shared layers*.\n",
    "Shared layers are layer instances that are reused multiple times in a same model --\n",
    "they learn features that correspond to multiple paths in the graph-of-layers.\n",
    "\n",
    "Shared layers are often used to encode inputs from similar spaces\n",
    "(say, two different pieces of text that feature similar vocabulary).\n",
    "They enable sharing of information across these different inputs,\n",
    "and they make it possible to train such a model on less data.\n",
    "If a given word is seen in one of the inputs,\n",
    "that will benefit the processing of all inputs that pass through the shared layer.\n",
    "\n",
    "To share a layer in the functional API, call the same layer instance multiple times.\n",
    "For instance, here's an `Embedding` layer shared across two different text inputs:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code",
    "id": "ny0KAxiJnNH1"
   },
   "outputs": [],
   "source": [
    "# Embedding for 1000 unique words mapped to 128-dimensional vectors\n",
    "shared_embedding = layers.Embedding(1000, 128)\n",
    "\n",
    "# Variable-length sequence of integers\n",
    "text_input_a = keras.Input(shape=(None,), dtype=\"int32\")\n",
    "\n",
    "# Variable-length sequence of integers\n",
    "text_input_b = keras.Input(shape=(None,), dtype=\"int32\")\n",
    "\n",
    "# Reuse the same layer to encode both inputs\n",
    "encoded_input_a = shared_embedding(text_input_a)\n",
    "encoded_input_b = shared_embedding(text_input_b)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "vfCEQtGYEIp5"
   },
   "source": [
    "## Extract and reuse nodes in the graph of layers\n",
    "\n",
    "Because the graph of layers you are manipulating is a static data structure,\n",
    "it can be accessed and inspected. And this is how you are able to plot\n",
    "functional models as images.\n",
    "\n",
    "This also means that you can access the activations of intermediate layers\n",
    "(\"nodes\" in the graph) and reuse them elsewhere --\n",
    "which is very useful for something like feature extraction.\n",
    "\n",
    "Let's look at an example. This is a VGG19 model with weights pretrained on ImageNet:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code",
    "id": "TdXUtSdAnENr"
   },
   "outputs": [],
   "source": [
    "vgg19 = tf.keras.applications.VGG19()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "a1iPac3p8ynf"
   },
   "source": [
    "And these are the intermediate activations of the model,\n",
    "obtained by querying the graph data structure:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code",
    "id": "rXdogI424cuE"
   },
   "outputs": [],
   "source": [
    "features_list = [layer.output for layer in vgg19.layers]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "usv9BSWNZDvz"
   },
   "source": [
    "Use these features to create a new feature-extraction model that returns\n",
    "the values of the intermediate layer activations:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code",
    "id": "q97Kw4uyLPe0"
   },
   "outputs": [],
   "source": [
    "feat_extraction_model = keras.Model(inputs=vgg19.input, outputs=features_list)\n",
    "\n",
    "img = np.random.random((1, 224, 224, 3)).astype(\"float32\")\n",
    "extracted_features = feat_extraction_model(img)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "lflgzfleXS12"
   },
   "source": [
    "This comes in handy for tasks like\n",
    "[neural style transfer](https://www.tensorflow.org/tutorials/generative/style_transfer),\n",
    "among other things."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "kSneSX5yF80u"
   },
   "source": [
    "## Extend the API using custom layers\n",
    "\n",
    "`tf.keras` includes a wide range of built-in layers, for example:\n",
    "\n",
    "- Convolutional layers: `Conv1D`, `Conv2D`, `Conv3D`, `Conv2DTranspose`\n",
    "- Pooling layers: `MaxPooling1D`, `MaxPooling2D`, `MaxPooling3D`, `AveragePooling1D`\n",
    "- RNN layers: `GRU`, `LSTM`, `ConvLSTM2D`\n",
    "- `BatchNormalization`, `Dropout`, `Embedding`, etc.\n",
    "\n",
    "But if you don't find what you need, it's easy to extend the API by creating\n",
    "your own layers. All layers subclass the `Layer` class and implement:\n",
    "\n",
    "- `call` method, that specifies the computation done by the layer.\n",
    "- `build` method, that creates the weights of the layer (this is just a style\n",
    "convention since you can create weights in `__init__`, as well).\n",
    "\n",
    "To learn more about creating layers from scratch, read\n",
    "[custom layers and models](https://www.tensorflow.org/guide/keras/custom_layers_and_models) guide.\n",
    "\n",
    "The following is a basic implementation of `tf.keras.layers.Dense`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code",
    "id": "AUZ6uTb8nAg7"
   },
   "outputs": [],
   "source": [
    "\n",
    "class CustomDense(layers.Layer):\n",
    "    def __init__(self, units=32):\n",
    "        super(CustomDense, self).__init__()\n",
    "        self.units = units\n",
    "\n",
    "    def build(self, input_shape):\n",
    "        self.w = self.add_weight(\n",
    "            shape=(input_shape[-1], self.units),\n",
    "            initializer=\"random_normal\",\n",
    "            trainable=True,\n",
    "        )\n",
    "        self.b = self.add_weight(\n",
    "            shape=(self.units,), initializer=\"random_normal\", trainable=True\n",
    "        )\n",
    "\n",
    "    def call(self, inputs):\n",
    "        return tf.matmul(inputs, self.w) + self.b\n",
    "\n",
    "\n",
    "inputs = keras.Input((4,))\n",
    "outputs = CustomDense(10)(inputs)\n",
    "\n",
    "model = keras.Model(inputs, outputs)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "8LYAUGIM6AZi"
   },
   "source": [
    "For serialization support in your custom layer, define a `get_config`\n",
    "method that returns the constructor arguments of the layer instance:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code",
    "id": "2qolaf41RnL3"
   },
   "outputs": [],
   "source": [
    "\n",
    "class CustomDense(layers.Layer):\n",
    "    def __init__(self, units=32):\n",
    "        super(CustomDense, self).__init__()\n",
    "        self.units = units\n",
    "\n",
    "    def build(self, input_shape):\n",
    "        self.w = self.add_weight(\n",
    "            shape=(input_shape[-1], self.units),\n",
    "            initializer=\"random_normal\",\n",
    "            trainable=True,\n",
    "        )\n",
    "        self.b = self.add_weight(\n",
    "            shape=(self.units,), initializer=\"random_normal\", trainable=True\n",
    "        )\n",
    "\n",
    "    def call(self, inputs):\n",
    "        return tf.matmul(inputs, self.w) + self.b\n",
    "\n",
    "    def get_config(self):\n",
    "        return {\"units\": self.units}\n",
    "\n",
    "\n",
    "inputs = keras.Input((4,))\n",
    "outputs = CustomDense(10)(inputs)\n",
    "\n",
    "model = keras.Model(inputs, outputs)\n",
    "config = model.get_config()\n",
    "\n",
    "new_model = keras.Model.from_config(config, custom_objects={\"CustomDense\": CustomDense})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "lWK2MF95UvRY"
   },
   "source": [
    "Optionally, implement the classmethod `from_config(cls, config)` which is used\n",
    "when recreating a layer instance given its config dictionary.\n",
    "The default implementation of `from_config` is:\n",
    "\n",
    "```python\n",
    "def from_config(cls, config):\n",
    "  return cls(**config)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "2uNRHpd1NRiY"
   },
   "source": [
    "## When to use the functional API\n",
    "\n",
    "When should you use the Keras functional API to create a new model,\n",
    "or just subclass the `Model` class directly? In general, the functional API\n",
    "is higher-level, easier and safer, and has a number of\n",
    "features that subclassed models do not support.\n",
    "\n",
    "However, model subclassing provides greater flexibility when building models\n",
    "that are not easily expressible as directed acyclic graphs of layers.\n",
    "For example, you could not implement a Tree-RNN with the functional API\n",
    "and would have to subclass `Model` directly.\n",
    "\n",
    "For in-depth look at the differences between the functional API and\n",
    "model subclassing, read\n",
    "[What are Symbolic and Imperative APIs in TensorFlow 2.0?](https://blog.tensorflow.org/2019/01/what-are-symbolic-and-imperative-apis.html).\n",
    "\n",
    "### Functional API strengths:\n",
    "\n",
    "The following properties are also true for Sequential models\n",
    "(which are also data structures), but are not true for subclassed models\n",
    "(which are Python bytecode, not data structures).\n",
    "\n",
    "#### Less verbose\n",
    "\n",
    "There is no `super(MyClass, self).__init__(...)`, no `def call(self, ...):`, etc.\n",
    "\n",
    "Compare:\n",
    "\n",
    "```python\n",
    "inputs = keras.Input(shape=(32,))\n",
    "x = layers.Dense(64, activation='relu')(inputs)\n",
    "outputs = layers.Dense(10)(x)\n",
    "mlp = keras.Model(inputs, outputs)\n",
    "```\n",
    "\n",
    "With the subclassed version:\n",
    "\n",
    "```python\n",
    "class MLP(keras.Model):\n",
    "\n",
    "  def __init__(self, **kwargs):\n",
    "    super(MLP, self).__init__(**kwargs)\n",
    "    self.dense_1 = layers.Dense(64, activation='relu')\n",
    "    self.dense_2 = layers.Dense(10)\n",
    "\n",
    "  def call(self, inputs):\n",
    "    x = self.dense_1(inputs)\n",
    "    return self.dense_2(x)\n",
    "\n",
    "# Instantiate the model.\n",
    "mlp = MLP()\n",
    "# Necessary to create the model's state.\n",
    "# The model doesn't have a state until it's called at least once.\n",
    "_ = mlp(tf.zeros((1, 32)))\n",
    "```\n",
    "\n",
    "#### Model validation while defining its connectivity graph\n",
    "\n",
    "In the functional API, the input specification (shape and dtype) is created\n",
    "in advance (using `Input`). Every time you call a layer,\n",
    "the layer checks that the specification passed to it matches its assumptions,\n",
    "and it will raise a helpful error message if not.\n",
    "\n",
    "This guarantees that any model you can build with the functional API will run.\n",
    "All debugging -- other than convergence-related debugging --\n",
    "happens statically during the model construction and not at execution time.\n",
    "This is similar to type checking in a compiler.\n",
    "\n",
    "#### A functional model is plottable and inspectable\n",
    "\n",
    "You can plot the model as a graph, and you can easily access intermediate nodes\n",
    "in this graph. For example, to extract and reuse the activations of intermediate\n",
    "layers (as seen in a previous example):\n",
    "\n",
    "```python\n",
    "features_list = [layer.output for layer in vgg19.layers]\n",
    "feat_extraction_model = keras.Model(inputs=vgg19.input, outputs=features_list)\n",
    "```\n",
    "\n",
    "#### A functional model can be serialized or cloned\n",
    "\n",
    "Because a functional model is a data structure rather than a piece of code,\n",
    "it is safely serializable and can be saved as a single file\n",
    "that allows you to recreate the exact same model\n",
    "without having access to any of the original code.\n",
    "See the [serialization & saving guide](https://www.tensorflow.org/guide/keras/save_and_serialize/).\n",
    "\n",
    "To serialize a subclassed model, it is necessary for the implementer\n",
    "to specify a `get_config()`\n",
    "and `from_config()` method at the model level.\n",
    "\n",
    "\n",
    "### Functional API weakness:\n",
    "\n",
    "#### It does not support dynamic architectures\n",
    "\n",
    "The functional API treats models as DAGs of layers.\n",
    "This is true for most deep learning architectures, but not all -- for example,\n",
    "recursive networks or Tree RNNs do not follow this assumption and cannot\n",
    "be implemented in the functional API."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "tYervQeJSYhE"
   },
   "source": [
    "## Mix-and-match API styles\n",
    "\n",
    "Choosing between the functional API or Model subclassing isn't a\n",
    "binary decision that restricts you into one category of models.\n",
    "All models in the `tf.keras` API can interact with each other, whether they're\n",
    "`Sequential` models, functional models, or subclassed models that are written\n",
    "from scratch.\n",
    "\n",
    "You can always use a functional model or `Sequential` model\n",
    "as part of a subclassed model or layer:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code",
    "id": "j7xQwfQnCd77"
   },
   "outputs": [],
   "source": [
    "units = 32\n",
    "timesteps = 10\n",
    "input_dim = 5\n",
    "\n",
    "# Define a Functional model\n",
    "inputs = keras.Input((None, units))\n",
    "x = layers.GlobalAveragePooling1D()(inputs)\n",
    "outputs = layers.Dense(1)(x)\n",
    "model = keras.Model(inputs, outputs)\n",
    "\n",
    "\n",
    "class CustomRNN(layers.Layer):\n",
    "    def __init__(self):\n",
    "        super(CustomRNN, self).__init__()\n",
    "        self.units = units\n",
    "        self.projection_1 = layers.Dense(units=units, activation=\"tanh\")\n",
    "        self.projection_2 = layers.Dense(units=units, activation=\"tanh\")\n",
    "        # Our previously-defined Functional model\n",
    "        self.classifier = model\n",
    "\n",
    "    def call(self, inputs):\n",
    "        outputs = []\n",
    "        state = tf.zeros(shape=(inputs.shape[0], self.units))\n",
    "        for t in range(inputs.shape[1]):\n",
    "            x = inputs[:, t, :]\n",
    "            h = self.projection_1(x)\n",
    "            y = h + self.projection_2(state)\n",
    "            state = y\n",
    "            outputs.append(y)\n",
    "        features = tf.stack(outputs, axis=1)\n",
    "        print(features.shape)\n",
    "        return self.classifier(features)\n",
    "\n",
    "\n",
    "rnn_model = CustomRNN()\n",
    "_ = rnn_model(tf.zeros((1, timesteps, input_dim)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "QQ0tleKoj3dH"
   },
   "source": [
    "You can use any subclassed layer or model in the functional API\n",
    "as long as it implements a `call` method that follows one of the following patterns:\n",
    "\n",
    "- `call(self, inputs, **kwargs)` --\n",
    "Where `inputs` is a tensor or a nested structure of tensors (e.g. a list of tensors),\n",
    "and where `**kwargs` are non-tensor arguments (non-inputs).\n",
    "- `call(self, inputs, training=None, **kwargs)` --\n",
    "Where `training` is a boolean indicating whether the layer should behave\n",
    "in training mode and inference mode.\n",
    "- `call(self, inputs, mask=None, **kwargs)` --\n",
    "Where `mask` is a boolean mask tensor (useful for RNNs, for instance).\n",
    "- `call(self, inputs, training=None, mask=None, **kwargs)` --\n",
    "Of course, you can have both masking and training-specific behavior at the same time.\n",
    "\n",
    "Additionally, if you implement the `get_config` method on your custom Layer or model,\n",
    "the functional models you create will still be serializable and cloneable.\n",
    "\n",
    "Here's a quick example of a custom RNN, written from scratch,\n",
    "being used in a functional model:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code",
    "id": "9NK579QrIbXv"
   },
   "outputs": [],
   "source": [
    "units = 32\n",
    "timesteps = 10\n",
    "input_dim = 5\n",
    "batch_size = 16\n",
    "\n",
    "\n",
    "class CustomRNN(layers.Layer):\n",
    "    def __init__(self):\n",
    "        super(CustomRNN, self).__init__()\n",
    "        self.units = units\n",
    "        self.projection_1 = layers.Dense(units=units, activation=\"tanh\")\n",
    "        self.projection_2 = layers.Dense(units=units, activation=\"tanh\")\n",
    "        self.classifier = layers.Dense(1)\n",
    "\n",
    "    def call(self, inputs):\n",
    "        outputs = []\n",
    "        state = tf.zeros(shape=(inputs.shape[0], self.units))\n",
    "        for t in range(inputs.shape[1]):\n",
    "            x = inputs[:, t, :]\n",
    "            h = self.projection_1(x)\n",
    "            y = h + self.projection_2(state)\n",
    "            state = y\n",
    "            outputs.append(y)\n",
    "        features = tf.stack(outputs, axis=1)\n",
    "        return self.classifier(features)\n",
    "\n",
    "\n",
    "# Note that you specify a static batch size for the inputs with the `batch_shape`\n",
    "# arg, because the inner computation of `CustomRNN` requires a static batch size\n",
    "# (when you create the `state` zeros tensor).\n",
    "inputs = keras.Input(batch_shape=(batch_size, timesteps, input_dim))\n",
    "x = layers.Conv1D(32, 3)(inputs)\n",
    "outputs = CustomRNN()(x)\n",
    "\n",
    "model = keras.Model(inputs, outputs)\n",
    "\n",
    "rnn_model = CustomRNN()\n",
    "_ = rnn_model(tf.zeros((1, 10, 5)))"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "collapsed_sections": [],
   "name": "functional.ipynb",
   "private_outputs": true,
   "provenance": [],
   "toc_visible": true
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}